#!/usr/bin/env bash
# Copyright 2020 The Tint Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# See https://clang.llvm.org/docs/SourceBasedCodeCoverage.html

if [ ! -x "$(which llvm-profdata)" ] ; then
    echo "error: llvm-profdata needs to be on \$PATH to use $0"
    exit 1
fi

if [ ! -x "$(which llvm-cov)" ] ; then
    echo "error: llvm-cov needs to be on \$PATH to use $0"
    exit 1
fi

TARGET_EXE=$1

if [ ! -x "$TARGET_EXE" ] ; then
    echo "Usage: $0 <executable-path> [optional-args]"
    echo ""
    echo "Generates a lcov.info file at the project root, which can be used by"
    echo "tools such as VSCode's Coverage Gutters extension to visualize code"
    echo "coverage in the editor".
    exit 1
fi

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd )"
ROOT_DIR="$( cd "${SCRIPT_DIR}/.." >/dev/null 2>&1 && pwd )"

PROFRAW_FILE="${ROOT_DIR}/tint.profraw"
PROFDATA_FILE="${ROOT_DIR}/tint.profdata"
LCOV_FILE="${ROOT_DIR}/lcov.info"
SUMMARY_FILE="${ROOT_DIR}/coverage.summary"

# Remove any existing coverage data and intermediate files
if [ -f "$PROFRAW_FILE"  ]; then rm ${PROFRAW_FILE};  fi
if [ -f "$PROFDATA_FILE" ]; then rm ${PROFDATA_FILE}; fi
if [ -f "$LCOV_FILE" ];     then rm ${LCOV_FILE};     fi
if [ -f "$SUMMARY_FILE" ];  then rm ${SUMMARY_FILE};  fi

# Run the executable to generate the raw coverage data
# https://clang.llvm.org/docs/SourceBasedCodeCoverage.html#running-the-instrumented-program
LLVM_PROFILE_FILE="${PROFRAW_FILE}" "$@"

# Check that coverage information was generated
if [ ! -f "$PROFRAW_FILE" ]; then
    echo "lcov.info was not generated. Is coverage generation enabled?"
    echo "To enable, run cmake with -DTINT_EMIT_COVERAGE=1".
    exit 1
fi

# Fail on any error after running the target executable
set -e

# Index the coverage data
# https://clang.llvm.org/docs/SourceBasedCodeCoverage.html#creating-coverage-reports
llvm-profdata merge -sparse "${PROFRAW_FILE}" -o "${PROFDATA_FILE}"

# Export as lcov
# https://clang.llvm.org/docs/SourceBasedCodeCoverage.html#exporting-coverage-data
llvm-cov export --instr-profile="${PROFDATA_FILE}" --format=lcov --object=${TARGET_EXE} > "${LCOV_FILE}"

# Generate summary report
llvm-cov report --ignore-filename-regex="(.*_test\.cc|third_party/.*)" --instr-profile="${PROFDATA_FILE}" --object=${TARGET_EXE} > "${SUMMARY_FILE}"

# Clean up intermediate files
rm ${PROFRAW_FILE} ${PROFDATA_FILE}
